<!--个人资料-->
<template>
    <el-tabs v-model="activeTab" type="border-card" style="height: 900px;">
        <el-tab-pane label="个人资料" name="userinfo">
            <el-row>
                <el-col :span="12">
                    <el-form :model="userform" ref="uform" :rules="rules" style="width: 500px; margin-left: 40px;">
                        <el-form-item label="用户账号" style="margin-top: 30px;">
                            <el-input disabled v-model="userform.account"></el-input>
                        </el-form-item> 
                        <el-form-item label="用户姓名" style="margin-top: 30px;" prop="name">
                            <el-input v-model="userform.name"></el-input>
                        </el-form-item> 
                        <el-form-item label="岗位名称" style="margin-top: 30px;">
                            <el-input disabled v-model="userform.position"></el-input>
                        </el-form-item> 
                        <el-form-item label="所在部门" style="margin-top: 30px;">
                            <el-input disabled v-model="userform.department"></el-input>
                        </el-form-item> 
                        <el-form-item label="性别" style="margin-top: 30px;margin-left: 30px;" prop="sex">
                            <el-radio-group v-model="userform.sex">
                                <el-radio label="男">男</el-radio>
                                <el-radio label="女">女</el-radio>
                            </el-radio-group>
                        </el-form-item> 
                        <el-form-item label="手机号" style="margin-top: 30px;" prop="phone">
                            <el-input v-model="userform.phone"></el-input>
                        </el-form-item> 
                        <el-form-item style="margin-top:60px;margin-left: 180px;">
                            <el-button type="danger">重置</el-button>
                            <el-button type="success" @click="UpdateInfo">保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="12" style="margin-left: -300px;margin-top: 30px;">
                    <!--头像-->
                    <el-upload
                        class="avatar-uploader"
                        action="http://localhost:5194/api/User/UploadAvatar"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :headers="headers">
                        <el-avatar :src="userform.avatar"  :size="150" fit="cover"></el-avatar>
                        <el-button style="margin-left: -120px;margin-top: 200px">更换头像</el-button>
                    </el-upload>
                </el-col>
            </el-row>
        </el-tab-pane>


        <!---------------------------------->
      <el-tab-pane label="修改密码" name="password">
        <el-form :model="pwdform" ref="pform" :rules="prules" style="width: 500px; margin-left: 30px;">
            <el-form-item label="原密码" style="margin-top: 30px;margin-left: 15px;" prop="oldpwd">
                <el-input v-model="pwdform.oldpwd"></el-input>
            </el-form-item> 
            <el-form-item label="新密码" style="margin-top: 30px;margin-left: 15px;" prop="newpwd">
                <el-input v-model="pwdform.newpwd"></el-input>
            </el-form-item> 
            <el-form-item label="确认密码" style="margin-top: 30px;" prop="okpwd">
                <el-input v-model="pwdform.okpwd"></el-input>
            </el-form-item> 
            <el-form-item style="margin-top:60px;margin-left: 180px;">
                <el-button @click="PReset">重置</el-button>
                <el-button @click="PUpdate" type="success">保存</el-button>
            </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
</template>

<script>
import {ref,reactive,onMounted} from 'vue';
import { ElMessage,ElMessageBox} from 'element-plus'; //提示信息
import http from '../auth/index';
import { useRouter, useRoute } from 'vue-router';//路由
export default {
setup()
    {
        const router = useRouter();//路由
        const route = useRoute();//路由参数

        // 当前激活的标签页
        const activeTab = ref('userinfo');

        // 监听路由参数，自动切换标签页
        onMounted(() => {
            if (route.query.activeTab === 'password') {
                activeTab.value = 'password';
            }
        });

        //用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        const userform=reactive({
            id:user.id,
            account:user.account,
            password:user.password,
            name:user.name,
            sex:user.sex,
            avatar:user.avatar,
            phone:user.phone,
            position:user.position,
            department:user.department
        })

         //用户信息验证规则
        const uform=ref("");
        const rules=reactive({
            name:[
                {required: true, message: '请输入用户账号', trigger: 'blur'},
                { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '请输入2-5位汉字', trigger: 'blur' }
            ],
            phone:[
                {required: true, message: '请输入校验码', trigger: 'blur'},
                { pattern: /^1[3-9]\d{9}$/, message: '请输入11位手机号,', trigger: 'blur' }
            ]
        });


        //密码信息
        const pwdform=reactive({
            oldpwd:"",
            newpwd:"",
            okpwd:"",
        })

         //密码验证规则
        const pform=ref("");
        const prules=reactive({
            oldpwd:[
                {required: true, message: '请输入原密码', trigger: 'blur'},
                { validator: validateOldPassword, trigger: 'blur' } 
            ],
            newpwd:[
                {required: true, message: '请输入新验码', trigger: 'blur'},
                { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
                { validator: validatePassword, trigger: 'blur' }
            ],
            okpwd:[
                {required: true, message: '请确认验码', trigger: 'blur'},
                { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
                { validator: validateConfirmPassword, trigger: 'blur' }
            ]
        });

        //判断原密码
        function validateOldPassword(rule, value, callback) {
            if (value !== user.password) {
                callback(new Error('原密码错误'));
            } else {
                callback();
            }
        }

        //判断密码格式
        function validatePassword(rule, value, callback) {
            const hasNumber = /\d/.test(value);
            const hasLetter = /[a-zA-Z]/.test(value);
            const hasUnderline = /_/.test(value);
            if (!hasNumber || !hasLetter || !hasUnderline) {
                callback(new Error('密码必须包含数字、字母和下划线'));
            } else {
                callback();
            }
        }

        //判断两次密码是否一致
        function validateConfirmPassword(rule, value, callback) {
            if (value !== pwdform.newpwd) {
                callback(new Error('两次输入密码不一致'));
            } else {
                callback();
            }
        }   

        //密码重置
        function PReset(){
            pform.value?.resetFields();
        }

        //密码修改
        function PUpdate(){
            pform.value.validate((valid)=>{
                if(valid){
                    http.put("/User/UpdatePwd?uid="+user.id+"&pwd="+pwdform.newpwd)
                    .then(res=>{
                        if(res.data>0){
                            ElMessageBox.alert('密码修改成功，请重新登录', '提示', {
                            confirmButtonText: 'OK',
                            callback: () => {
                                router.push("/login");
                            },
                        })
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            })
        }


        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传前验证方法
        function beforeAvatarUpload(file) {
            // 定义允许的图片格式
            const allowedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];
            const isImage = allowedFormats.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                ElMessage.error('仅支持 JPEG、PNG、GIF、BMP 格式的图片文件!');
            }
            if (!isLt2M) {
                ElMessage.error('图片大小不能超过 2MB!');
            }
            return isImage && isLt2M;
        }

        // 上传成功回调方法
        function handleAvatarSuccess(response) {
            if (response.success) {
                ElMessage.success('头像更新成功');
                userform.avatar = response.path;
                console.log(userform.avatar)
            } else {
                ElMessage.error('头像更新失败');
            }
        }


        //修改个人信息
        function UpdateInfo(){
            http.put("/User/UpdateInfo?name="+userform.name+"&sex="+userform.sex+"&avatar="+userform.avatar+"&phone="+userform.phone+"&id="+userform.id).then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '修改成功.',
                        type: 'success',
                    })
                    // 刷新整个页面
                    location.reload();
                }else{
                    ElMessage.error('修改失败.')
                }
            }).catch(err=>{
                console.log(err)
            })
        }


        return{
            user,
            userform,
            uform,
            rules,
            pwdform,
            pform,
            prules,
            PReset,
            PUpdate,
            router,
            beforeAvatarUpload,
            handleAvatarSuccess,
            headers,
            UpdateInfo,
            activeTab
        }
    }
}
</script>

<style scoped>

</style>